package org.ru.mse10.cvis.service;

import java.util.List;

import javax.ejb.Stateful;
import javax.persistence.Query;

import org.ru.mse10.cvis.constants.CodeValueQueries;
import org.ru.mse10.cvis.entity.codelists.Codelist;
import org.ru.mse10.cvis.entity.codelists.CodelistValue;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class CodelistService.
 */
@Stateful
public class CodelistService extends EntityService {

	/**
	 * Retrieve values for codelist.
	 * 
	 * @param cl
	 *            the cl
	 * @return the list
	 */
	@SuppressWarnings("unchecked")
	public List<CodelistValue> retrieveValuesForCodelist(String cl) {
		return getEntityManager()
				.createNamedQuery(CodeValueQueries.QUERY_CV_OF_CL_KEY)
				.setParameter("cl", cl).getResultList();
	}

	/**
	 * Returns code list (language support).
	 * 
	 * @param code
	 *            code of the code list
	 * @return the code list
	 */
	public Codelist retrieveCodelistByCode(String code) {
		Query query = getEntityManager().createNamedQuery(
				CodeValueQueries.QUERY_CODELIST_BY_CODE_KEY);
		query.setParameter("cl", code).getResultList();
		return (Codelist) query.getSingleResult();

	}

	/**
	 * Gets the codelist value.
	 * 
	 * @param cl
	 *            the cl
	 * @param clv
	 *            the clv
	 * @param lang
	 *            the lang
	 * @return the codelist value
	 */
	public String getCodelistValue(String cl, String clv, String lang) {
		Query query = getEntityManager()
				.createQuery(
						"from CodelistValue cv inner join fetch cv.codelist cl where cv.code = :clv and cl.code = :cl");
		query.setParameter("cl", cl);
		query.setParameter("clv", clv);
		@SuppressWarnings("unchecked")
		List<CodelistValue> list = query.getResultList();
		if (!CommonUtil.isEmpty(list)) {
			return list.get(0).getTranslatedValues().get(lang).getValue();
		}
		return "";
	}
}
